<template>
  <div class="user-management">
    <!-- 顶部操作按钮区 -->
    <el-card style="height:620px">
      <div class="header">
        <el-button-group class="operation-buttons">
          <el-button @click="openAddDialog">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
          <!-- 保留导入/导出按钮 -->
          <el-button>
            <el-icon><Download /></el-icon>
            导入
          </el-button>
          <el-button>
            <el-icon><Upload /></el-icon>
            导出
          </el-button>
        </el-button-group>

        <!-- 搜索框 -->
        <div class="search-container">
          <el-input
              placeholder="请输入搜索内容"
              v-model="searchText"
              @keyup.enter.native="handleSearch"
              class="search-input"
          >
          </el-input>
          <el-button
              type="primary"
              @click="handleSearch"
              class="search-button"
          >
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </div>
      </div>

      <!-- 用户表格 -->
      <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%; margin-top: 20px"
          max-height="calc(100vh - 180px)"
      >
        <el-table-column
            prop="id"
            label="ID"
            width="120"
        ></el-table-column>
        <el-table-column
            prop="username"
            label="账号"
            width="210"
        ></el-table-column>
        <el-table-column
            prop="name"
            label="用户名称"
            width="210"
        ></el-table-column>
        <el-table-column
            prop="sex"
            label="性别"
            width="200"
        ></el-table-column>
        <el-table-column
            prop="roleName"
            label="角色名称"
            width="210"
        ></el-table-column>
        <el-table-column
            prop="creationTime"
            label="创建时间"
            width="260"
        ></el-table-column>
        <el-table-column
            label="操作"
            width="250px"
            fixed="right"
        >
          <template #default="{ row }">
            <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination">
        <span>共 {{total}} 条</span>
        <span> </span>
        <el-pagination
            background
            layout="prev, pager, next"
            :page-size="10"
            :current-page="currentPage"
            :total="total"
            @current-change="handlePageChange"
        >
        </el-pagination>
      </div>

    </el-card>

    <!-- 添加用户弹窗 -->
    <el-dialog
        v-model="addDialogVisible"
        title="新增用户"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addFormRules"
          label-width="80px"
          class="dialog-form"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="用户名称" prop="nickname">
          <el-input v-model="addForm.nickname" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="普通用户" value="user"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="addForm.password"
              type="password"
              autocomplete="new-password"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户弹窗（新增部分） -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑用户"
        width="500px"
        @close="handleEditDialogClose"
    >
      <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="80px"
          class="dialog-form"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="用户名称" prop="nickname">
          <el-input v-model="editForm.nickname" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">

            <el-option v-for="(item,index) in roleList" :key="index" :label="item.roleName" :value="item.roleId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {getUserInfo,updateUser,getUser,deleteUser} from "@/api/User.js"
import {selectRoleList} from '@/api/Role.js'
export default {
  name: 'UserManagement',
  setup() {
    // 用户列表数据
    const tableData = ref([]);
    // 总记录数
    const total = ref(0);
    // 当前页码
    const currentPage = ref(1);
    // 搜索文本
    const searchText = ref('');
    const params = {
      name: searchText.value,
      pageNum: currentPage.value,
      pageSize: 6
    };
    const roleList = ref([]);

    // 获取用户列表
    const getList = () => {
      getUserInfo(params).then((res) => {
        if (res.code == '200') {
          tableData.value = res.data.list;
          total.value = res.data.count;
          console.log(res)
        }
        console.log('获取用户列表成功', tableData.value)
      }).catch((error) => {
        console.error('获取用户列表失败', error);
        ElMessage.error('请检查网络或重试');
      });
    };
    const getRoleList = async () => {
      const roleres = await selectRoleList();

      roleList.value = roleres.data;
    }


    // 组件挂载后获取数据
    onMounted(() => {
      getRoleList()
      getList();
    });

    // 处理搜索
    const handleSearch = () => {
      console.log('搜索内容:', searchText.value);
      params.pageNum = 1;
      getList();
    };


    // 处理编辑
    const handleEdit = async (row) => {
      console.log('编辑用户:', row);
      editDialogVisible.value = true;
      const res = await getUser(row.id);



    };


    // 处理删除
    const handleDelete = async (row) => {
      console.log('删除用户:', row);
      try {
        await deleteUser(row.id);
        ElMessage.success('删除成功');
      }catch (error){
        ElMessage.error('删除失败');
      }
    };

    // 处理分页
    const handlePageChange = (page) => {
      currentPage.value = page;
      getList();
    };

    // 添加用户弹窗相关
    const addDialogVisible = ref(false);
    const addForm = ref({
      username: '',
      nickname: '',
      sex: '男',
      role: 'user',
      password: ''
    });
    const addFormRules = reactive({
      username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度6 - 20位', trigger: 'blur' }
      ]
    });
    const addFormRef = ref(null);

    // 编辑用户弹窗相关
    const editDialogVisible = ref(false);
    const editForm = ref({});
    const editFormRules = reactive({
      username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
      ]
    });
    const editFormRef = ref(null);

    // 打开添加弹窗
    const openAddDialog = () => {
      addDialogVisible.value = true;
      // 重置表单
      const resetForm = () => {
        addForm.value = {
          username: '',
          nickname: '',
          sex: '男',
          role: 'user',
          password: ''
        };
      };
      resetForm();
    };

    // 关闭添加弹窗时重置表单
    const handleDialogClose = () => {
      const resetForm = () => {
        addForm.value = {
          username: '',
          nickname: '',
          sex: '男',
          role: 'user',
          password: ''
        };
      };
      resetForm();
      addFormRef.value?.resetFields();
    };

    // 处理用户添加
    const handleAddUser = async () => {
      await addFormRef.value?.validate(valid => {
        if (!valid) return;
        const newUser = {
          username: addForm.value.username,
          nickname: addForm.value.nickname,
          sex: addForm.value.sex,
          role: addForm.value.role,
          password: addForm.value.password
        };

      });
    };

    // 关闭编辑弹窗时重置表单
    const handleEditDialogClose = () => {
      const resetForm = () => {
        editForm.value = {};
      };
      resetForm();
      editFormRef.value?.resetFields();
    };

    // 处理用户编辑
    const handleEditUser = async () => {
      await editFormRef.value?.validate(valid => {
        if (!valid) return;
        const editUser = {
          id: editForm.value.id,
          username: editForm.value.username,
          nickname: editForm.value.nickname,
          sex: editForm.value.sex,
          role: editForm.value.role
        };

      });
    };

    return {
      tableData,
      searchText,
      handleSearch,
      handleEdit,
      handleDelete,
      addDialogVisible,
      addForm,
      addFormRules,
      openAddDialog,
      handleDialogClose,
      handlePageChange,
      addFormRef,
      handleAddUser,
      total,
      currentPage,
      editDialogVisible,
      editForm,
      editFormRules,
      handleEditDialogClose,
      handleEditUser
    };
  }
};
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.operation-buttons button {
  margin-right: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  width: 320px;
}

.search-input {
  flex: 1;
  margin-right: 10px;
}

.el-table th {
  background-color: #f5f7fa;
}

.el-table td, .el-table th {
  text-align: center;
}

.el-button--primary {
  color: #409eff;
  background-color: #ecf5ff;
  border-color: #d9ecff;
}

.el-button--danger {
  color: #fff;
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-table .cell {
  /*  文字左右居中*/
  text-align: center;
}

/* 使用深度选择器确保样式生效 */
::v-deep .el-table th,
::v-deep .el-table td {
  text-align: center;
  vertical-align: middle;
  padding: 10px 0;
  font-size: 14px;
  border-bottom: 1px solid #eee;
}

/* 弹窗表单样式 */
.dialog-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-radio-group {
  display: flex;
  gap: 10px;
}

.el-select {
  width: 100%;
}

.el-input {
  width: 100%;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
